package cn.pzhu.services.web;

import cn.pzhu.constant.ConstantLogin;
import cn.pzhu.model.User;
import cn.pzhu.services.BaseServices;
import cn.pzhu.util.EncryptUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by dongp on 2016/5/6.
 */
public class AccountServices extends BaseServices {

    public int login(String account, String password,HttpServletRequest request) {
        List<User> users = User.dao.find("select * from user where account = ?", account);
        if(users == null || users.size() != 1) {
            request.setAttribute("msg","用户名或密码不正确");
            return ConstantLogin.login_info_0;// 用户不存在
        }
        User user = users.get(0);

        // 如果密码错误，则错误次数加1并保存
        int errorCount = user.getInt(User.column_errorcount).intValue();
        int maxCount = user.getInt(User.column_maxcount).intValue();
        boolean checkSign = EncryptUtil.checkSign(password,user.getStr(User.column_password),"MD5");
        if(!checkSign) {
            errorCount++;
            user.findById(user.getInt("userID")).set(User.column_errorcount, errorCount).update();
            request.setAttribute("errorCount", maxCount - errorCount);
            request.setAttribute("msg","用户名或密码不正确");
            return ConstantLogin.login_info_2;// 密码错误
        }

        // 密码错误次数超限
        if(errorCount > maxCount) {
            request.setAttribute("msg","用户已被锁定，请联系管理员");
            return ConstantLogin.login_info_3;
        }

        HttpSession session = request.getSession();
        session.setAttribute("user",user);
        return ConstantLogin.login_info_1;// 用户验证成功
    }

    public boolean registry(String account, String password,HttpServletRequest request) {
        // 检查是否重复
        User user = User.dao.findFirst("select count(*) total from user where account = ?", account);
        Long total = user.getLong("total").longValue();
        if(total > 0) {
            request.setAttribute("msg","该账户已存在!");
            return false;
        }

        String encryptPassword = EncryptUtil.createSign(password,"MD5");
        boolean result = new User().set("userName","").set("account", account).set("password",encryptPassword)
                .set("errorCount",0).set("maxCount",10).set("roleVal", 1).save();

        return result;
    }
}
